package com.geping.etl.common.service.impl;

import com.geping.etl.common.entity.Report_Info;
import com.geping.etl.common.entity.Sys_Auth_Role_Resource;
import com.geping.etl.common.entity.Sys_Subject;
import com.geping.etl.common.entity.Sys_UserAndOrgDepartment;
import com.geping.etl.common.service.Report_InfoService;
import com.geping.etl.common.service.SysUserReportService;
import com.geping.etl.common.service.Sys_Auth_Role_ResourceService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysUserReportServiceImpl implements SysUserReportService {

    @Autowired
    private Sys_Auth_Role_ResourceService sarrs;

    @Autowired
    private Report_InfoService reprotinfoservice;

    @Override
    public List<Report_Info> queryUserReport(HttpServletRequest request) {
        Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
        return queryUserReportById(request, sys_User.getId());
    }

    @Override
    public List<Report_Info> queryUserReportById(HttpServletRequest request, Integer userId) {
        List<Sys_Subject> subjectList = (List<Sys_Subject>) request.getSession().getAttribute("subjectId");
        String subjectId = String.valueOf(subjectList.get(0).getId());
        List<Sys_Auth_Role_Resource> resourceList = sarrs.findResourceByRoleAndSubject(String.valueOf(userId), subjectId).stream().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(resourceList)) {
            return new ArrayList<>();
        }
        Map<String, Sys_Auth_Role_Resource> sys_Auth_Role_ResourceMap = new HashMap<>();
        for (int i = 0; i < resourceList.size(); i++) {
            Sys_Auth_Role_Resource resource = resourceList.get(i);
            if (resource.getResType().equals("Report")) {
                sys_Auth_Role_ResourceMap.put(resource.getResValue(), resource);
            }
        }
        List<Report_Info> roleList = reprotinfoservice.getReportBySubjectId(subjectId, "");
        roleList = roleList.stream().filter(report -> Objects.nonNull(sys_Auth_Role_ResourceMap.get(report.getCode()))).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(roleList)){
            return new ArrayList<>();
        }
        return roleList;
    }
}